import themes, { mix } from '@/themes';
import { generate } from '@ant-design/colors';

const { dependencies, tinyColor } = themes;

// eval解析中会用到
export const fade = (colorStr: string, alpha: number): string => tinyColor(colorStr).setAlpha(alpha).toRgbString();

// eval解析中会用到
export const darken = (colorStr: string, weight?: number): string => mix('000', colorStr, weight);

// eval解析中会用到
export const tint = (colorStr: string, weight?: number): string => mix('fff', colorStr, weight);

export const extract = (cssStr: string, position: number): string => cssStr.split(' ')[position - 1];

// eval解析中会用到
const paletteColorsTemp = {};
export const palette = (colorStr: string, weight?: number): string => {
  if (paletteColorsTemp[`${colorStr}-${weight}`]) {
    return paletteColorsTemp[`${colorStr}-${weight}`];
  }
  const colorPalettes = generate(colorStr);
  colorPalettes.forEach((color, i) => {
    paletteColorsTemp[`${colorStr}-${i + 1}`] = color;
  });
  return paletteColorsTemp[`${colorStr}-${weight}`];
};

export const shade = darken;

// 给html设置行内css变量
const setCssVar = (stylesT: object) => {
  const cssStr = Object.entries(stylesT)
    .map(([key, val]) => `${key}:${val}`)
    .join(';');
  document.documentElement.setAttribute('style', cssStr);
};

class ThemeColor {
  // 静态属性存储唯一实例
  static instance;

  // 单例模式
  constructor(styles) {
    // 如果已有实例，直接返回
    if (ThemeColor.instance) {
      return ThemeColor.instance;
    }
    // 初始化实例属性
    this.styles = styles;
    // 存储实例
    ThemeColor.instance = this;
  }

  generateCssVars(cssVars) {
    for (const stylePropName in cssVars) {
      const isFun = typeof cssVars[stylePropName] === 'function';
      const key = isFun ? cssVars[stylePropName](cssVars) : cssVars[stylePropName];
      this.styles[stylePropName] = key;
      if (dependencies[stylePropName]) {
        const dependence = dependencies[stylePropName];
        dependence.forEach((de = {}) => {
          if (typeof de === 'string') {
            this.styles[de] = key;
          } else {
            // eval直接调用当前页面的方法
            const ret = eval(de?.rule);
            if (de?.keys && de?.keys?.length) {
              de.keys.forEach((dk) => {
                this.styles[dk] = ret;
              });
            } else {
              this.styles[de?.key] = ret;
            }
          }
        });
      }
    }
  }

  changeSomeCssVars(cssVars: object) {
    this.generateCssVars(cssVars);
    setCssVar(this.styles);
  }

  changeTheme(themeName: string, otherConfig: object) {
    const cssVars = themes[themeName];
    this.generateCssVars(cssVars);
    this.generateCssVars(otherConfig);
    setCssVar(this.styles);
  }

  // 静态方法获取实例（另一种获取实例的方式）
  static getInstance(data) {
    if (!ThemeColor.instance) {
      ThemeColor.instance = new ThemeColor(data);
    }
    return ThemeColor.instance;
  }
}

// 导出单例实例（推荐）
export const ThemeColorInstance = new ThemeColor({});
// 也可以导出类本身（但需提醒使用者通过 getInstance() 获取）
export default ThemeColor;
